package com.offcn.play.controller;

import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.order.feign.OrderFeign;
import com.offcn.order.pojo.PayLog;
import com.offcn.play.service.PayService;
import com.offcn.utils.IdWorker;
import com.offcn.utils.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class Paycontroller {

    @Autowired
    private PayService payService;

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private TokenDecode tokenDecode;

    @RequestMapping("/createCode")
    public Map createCode() {

        /*IdWorker idWorker = new IdWorker();
        return payService.createCode(idWorker.nextId() + "", "1");
        */
        //获取用户名称
        String username = tokenDecode.getinfo().get("username");
        //当redis 中查询 支付日志
        Result<PayLog> result = orderFeign.findPayLog(username);
        PayLog payLog = result.getData();
        if (payLog!=null){
            return payService.createCode(payLog.getOutTradeNo(), payLog.getTotalFee()+"");
        }else {
            return null;
        }
    }


    @RequestMapping("/querStatus")
    public Result querPayStatus(String out_trade_no) {
        Result result = null;
        int x = 0;
        //循环调用 我们让二维码一直生成中
        while (true) {
            Map<String, String> map = null;
            try {
                map = payService.queryPayStatus(out_trade_no);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (map == null) {
                result = new Result(false, StatusCode.ERROR, "支付失败");
                break;
            }

            if (map.get("tradeStatus") != null && map.get("tradeStatus").equals("TRADE_SUCCESS")) {
                orderFeign.updateOrderStatus(map.get("out_trade_no"),map.get("trade_no"));
                result = new Result(true, StatusCode.OK, "支付成功");
                break;
            }
            if (map.get("tradeStatus") != null && map.get("tradeStatus").equals("TRADE_FINISHED")) {
                result = new Result(false, StatusCode.ERROR, "交易结束，不可退款");
                break;
            }
            if (map.get("tradeStatus") != null && map.get("tradeStatus").equals("TRADE_CLOSED")) {
                result = new Result(false, StatusCode.ERROR, "未付款交易超时关闭，或支付完成后全额退款");
                break;
            }


            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            x++;
            if (x >= 180) {
                result = new Result(false, StatusCode.ERROR, "二维码超时，请重新发送订单");
                break;
            }
        }

        return result;
    }
}
